<script setup lang="ts">
import type { ElTree } from "element-plus";
import type { RoleListResult } from "@/api/types";
import { watch } from "vue";
import { $t } from "@/plugins/i18n";
import { useRoleAssignTree } from "../composables";

export interface Props {
    visible?: boolean;
    role?: RoleListResult | null;
}

const props = withDefaults(defineProps<Props>(), {
    visible: false,
    role: null,
});

const emit = defineEmits<{
    (e: "update:visible", value: boolean): void;
}>();

const {
    treeRef,
    treeLoading,
    treeData,
    checkStrictly,
    isExpanded,
    expandAll,
    collapseAll,
    initData,
    submitLoading,
    resetTree,
    handleSubmit,
} = useRoleAssignTree();

watch(
    () => props.visible,
    (val) => {
        val ? initData(props.role?.id) : resetTree();
    },
);

function handleClose() {
    emit("update:visible", false);
}
</script>

<template>
    <el-drawer
        :model-value="visible"
        :title="$t('title.assignPermissions')"
        size="480px"
        destroy-on-close
        @close="handleClose"
    >
        <div class="mb-3">
            {{ $t("label.currentRole") }}: {{ role?.name ?? "-" }}
        </div>
        <div class="flex items-center mb-3">
            <el-button size="small" @click="expandAll">
                {{ $t("button.expandAll") }}
            </el-button>
            <el-button size="small" @click="collapseAll">
                {{ $t("button.collapseAll") }}
            </el-button>
            <el-checkbox v-model="checkStrictly" class="ml-3">
                层级独立
            </el-checkbox>
        </div>
        <div v-loading="treeLoading" class="flex-1 min-h-0 p-2 border border-(--el-border-color) overflow-auto">
            <el-tree
                v-if="treeData.length"
                ref="treeRef"
                :data="treeData"
                :props="{ children: 'children', label: 'meta.title' }"
                node-key="id"
                show-checkbox
                :default-expand-all="isExpanded"
                :check-strictly="checkStrictly"
                :expand-on-click-node="false"
            >
                <template #default="{ data }">
                    <span>{{ $t(data.meta?.title) }}</span>
                </template>
            </el-tree>
            <el-empty v-else class="py-10" :description="$t('status.noData')" />
        </div>
        <template #footer>
            <div class="text-right">
                <el-button @click="handleClose">
                    {{ $t("button.cancel") }}
                </el-button>
                <el-button
                    type="primary"
                    :loading="submitLoading" @click="() => handleSubmit(props.role?.id, handleClose)"
                >
                    {{ $t("button.confirm") }}
                </el-button>
            </div>
        </template>
    </el-drawer>
</template>
